<template>
    <div class="params-container">
         <!-- 导航区域 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
           <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>权限管理</el-breadcrumb-item>
           <el-breadcrumb-item>角色列表</el-breadcrumb-item>
         </el-breadcrumb>

           <!-- 卡片视图 -->
           <el-card>
             <!-- 警告框 -->
                 <el-alert title="注意：只能给三级的加信息" type="warning" description="因为三级是你爹" show-icon :closable = "false">
                 </el-alert>

                 <!-- 级联选择框 -->
                 <el-form>
                 <el-form-item label="选择商品分类">
                     <!-- :options 是用来指明数据源的 -->
                     <!-- props是用来配置节点选择框的 -->
                     <!-- v-model可以把咱们选定的那些id值双向绑定到数据中 -->
                     <!-- change选择项改变的事项 -->
                   <el-cascader :options="catelist" :props="catelistprops" v-model="catelistmodel" expandTrigger='hover' @change="handleChange" clearable></el-cascader>
                 </el-form-item>
                 </el-form>
                 
                    <!-- tag标签 -->
                  <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="动态参数" name="many">
                      <el-button type="primary" :disabled="btnsDisabled" @click="dialogVisible = true">添加参数</el-button>
                      <!-- 动态参数表格 -->
                       <el-table :data="manyTableData" border stripe style="width: 100%"> 
                         <el-table-column type="expand" width="60">
                           <template slot-scope="scope">
                             
                             <!-- 循环渲染tag标签 -->
                            <el-tag v-for="(item, i) in scope.row.attr_vals" :key = "i" closable @close = closeHand(i,scope.row)>{{item}}</el-tag>

                            <!-- 添加动态按钮 -->
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                              size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                              @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                              New Tag
                            </el-button>

                           </template>
                         </el-table-column>
                         <el-table-column label="" width="60">
                         </el-table-column>
                         <el-table-column type="index" label="#" width="60">
                         </el-table-column>
                         <el-table-column prop="attr_name" label="参数名称">
                         </el-table-column>
                         <el-table-column label="操作" width="220">
                           <template slot-scope="scope">
                             <el-button type="primary" icon="el-icon-edit" size="small"
                               @click="editdialog(scope.row.attr_id)">编辑
                             </el-button>
                             <el-button type="danger" icon="el-icon-delete" size="small"
                               @click="deleteBtns(scope.row.attr_id)">删除</el-button>
                           </template>
                         </el-table-column>
                       </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="静态属性" name="only">
                      <el-button type="primary" :disabled="btnsDisabled" @click="dialogVisible = true">添加属性</el-button>
                      <!-- 静态表格 -->
                      <el-table :data="onlyTableDate" border stripe style="width: 100%">
                         <el-table-column type="expand" width="60">
                           <template slot-scope="scope">

                             <!-- 循环渲染tag标签 -->
                             <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                               @close=closeHand(i,scope.row)>{{item}}</el-tag>

                             <!-- 添加动态按钮 -->
                             <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                               v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                               @keyup.enter.native="handleInputConfirm(scope.row)"
                               @blur="handleInputConfirm(scope.row)">
                             </el-input>
                             <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                               New Tag
                             </el-button>

                           </template>
                         </el-table-column>
                        <el-table-column label="" width="60">
                        </el-table-column>
                        <el-table-column type="index" label="#" width="60">
                        </el-table-column>
                        <el-table-column prop="attr_name" label="属性名称">
                        </el-table-column>
                        <el-table-column label="操作" width="220">
                          <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="small"
                              @click="editdialog(scope.row.attr_id)">编辑
                            </el-button>
                            <el-button type="danger" icon="el-icon-delete" size="small"
                              @click="deleteBtns(scope.row.attr_id)">删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-tab-pane>
                  </el-tabs>

                  <!-- 添加参数/属性弹出框 -->
                  <el-dialog :title="addParams" :visible.sync="dialogVisible" width="30%" @close="closeAddParams">
                  
                    <el-form :model="testModel" :rules="rules" ref="ruleForm" label-width="100px">
                      <el-form-item label="添加名称" prop="attr_name">
                        <el-input v-model="testModel.attr_name"></el-input>
                      </el-form-item>
                    </el-form>
                    <span slot="footer">
                      <el-button @click="dialogVisible = false">取 消</el-button>
                      <el-button type="primary" @click="requestPost">确 定</el-button>
                    </span>
                  </el-dialog>

                  <!-- 编辑按钮弹出框 -->
                 <el-dialog :title="addParams" :visible.sync="editdialogsss" width="30%" @close="editorParamsAddParams">
                   
                    <el-form :model="editModel" :rules="editrules" ref="editForm" label-width="100px">
                      <el-form-item label="添加名称" prop="attr_name">
                        <el-input v-model="editModel.attr_name"></el-input>
                      </el-form-item>
                    </el-form>

                   <span slot="footer" >
                     <el-button @click="editdialogsss = false">取 消</el-button>
                     <el-button type="primary" @click="editDetermineBtns">确 定</el-button>
                   </span>
                 </el-dialog>

           </el-card>
    </div>
</template>


<script>
export default {
    data(){
        return{
                catelist:[],

                // 配置节点选择框的
                catelistprops: {
                    value:'cat_id',
                    label:'cat_name',
                    children:'children'
                },

                catelistmodel:[],
                activeName: 'many',
                manyTableData:[],
                onlyTableDate:[],
                dialogVisible: false,
                editdialogsss: false,
                testModel:{
                  attr_name:''
                },
                rules:{
                   attr_name: [
                   { required: true, message: '该项是必填项', trigger: 'blur' },
                   { min: 2, max: 115, message: '请输入至少两位字符', trigger: 'blur' }
                   ],
                },
                editModel: {
                   attr_name:''
                },
                  editrules:{
                  attr_name: [
                  { required: true, message: '该项是必填项', trigger: 'blur' },
                  { min: 2, max: 115, message: '请输入至少两位字符', trigger: 'blur' }
                  ],
                  },
                }
              },

            created(){
                this.goodsCategories()
            },


            methods:{
             async  goodsCategories(){
                 const{data: res}  = await this.$http.get('categories')

                 if(res.meta.status !== 200){
                    return this.$message.error('失败')
                 }
                    this.catelist = res.data
                    // console.log( this.catelist);
               },

                // 级联选择框变化会触发这个函数
               handleChange(){
                    this.paramslist()
               },


              // 获取参数的列表数据
              //  自己封装的函数在其他的两个函数调用，因为直接写在其他两个里面不管用    为什么自己封装完了要在下面调用
              async paramslist(){
                    if(this.catelistmodel.length !==3){
                    this.catelistmodel = []
                    this.manyTableData = []
                    this.onlyTableDate = []     
                    return
                    }else{
                    // 里面有${}要加模板字符串
                    const{data: res} = await this.$http.get(`categories/${this.btnsParameter}/attributes`,{params:{sel:this.activeName} })

                    if(res.meta.status !== 200){ return this.$message.error('失败')} this.$message.success('成功')
                        // console.log(res.data);
                      res.data.forEach(item => {
                        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [ ]
                        // 控制文本框的显示与隐藏
                        item.inputVisible = false
                        // 文本框中输入的值
                        item.inputValue = ''
                      })

                      if(this.activeName === 'many'){
                        this.manyTableData = res.data
                      }
                      this.onlyTableDate = res.data 
                    }
                  },

                handleClick() {
                  //  console.log(this.activeName);
                  this.paramslist()
                },

                closeAddParams(){
                  this.$refs.ruleForm.resetFields()
                },

                editorParamsAddParams(){
                  this.$refs.editForm.resetFields()
                },
                


                // 添加参数 || 点击确定按钮进行post请求
                requestPost(){
                  // 再进行请求之前先进行验证，下面的箭头函数是起验证作用的，如果验证成功则进项请求
                  this.$refs.ruleForm.validate(async valid => {
                    if(!valid) return
                  // 发起请求保存这次操作
                  const {data: res} = await this.$http.post(`categories/${this.btnsParameter}/attributes`,{attr_sel:this.activeName, 
                  attr_name: this.testModel.attr_name})

                  if(res.meta.status !== 201){
                    return this.$message.error('添加分类失败')
                  }else{
                    this.$message.success('添加分类成功')
                  }
                  this.dialogVisible = false
                  this.paramslist()
                  })
                },

              // 点击按钮展示编辑对话框
              async editdialog (attr_id){
               const {data: res} =  await this.$http.get(`categories/${this.btnsParameter}/attributes/${attr_id}`,{
                 params:{
                    attr_sel: this.activeName}
                    })

                  if(res.meta.status !== 200) {
                    return this.$message.error('编辑失败')
                  }
                    this.$message.success('编辑成功')

                    this.editModel = res.data
                    this.editdialogsss = true
                },
                
                // 点击编辑按钮进行修改内容
               editDetermineBtns(){
                  this.$refs.editForm.validate(async(valid) => {
                    if(!valid){
                      return 
                    }else{
                    const{data: res} =  await this.$http.put(`categories/${this.btnsParameter}/attributes/${this.editModel.attr_id}`,{
                        attr_name:this.editModel.attr_name,
                        attr_sel:this.activeName,
                      })
                      this.paramslist()
                    }
                  })
                  this.editdialogsss = false
                },



          // 删除按钮弹出框
           async deleteBtns(attr_id){
             const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
               }).catch(err => err)

                // 用户取消了操作
               if(confirmResult !== 'confirm'){
                 return this.$message.error('取消删除')
               }

              //  删除操作
              const {data:res} = await this.$http.delete(`categories/${this.btnsParameter}/attributes/${attr_id}`)
                if(res.meta.status !== 200){
                return this.$message.error('删除失败')
                }else{
                this.$message.success('删除成功')
                }
                this.paramslist()
            },

            // 文本框失去焦点或摁下enter 都会触发
           async handleInputConfirm(row){ 
             console.log(row);
              if(row.inputValue.trim().length === 0){
                row.inputValue = ''
                row.inputVisible = false;
                return
              } 
              //如果没有return，则输入的内容需要做后续的处理
              row.attr_vals.push(row.inputValue.trim())
              row.inputValue = ''
              row.inputVisible = false

            // 发起请求保存数据
            this.saveAttrVals(row)

            },
        

          // 将对attr_vals的操作保存到数据库

           async saveAttrVals(row){
                // 发起请求保存数据
                const {data: res} = await this.$http.put(`categories/${this.btnsParameter}/attributes/${row.attr_id}`,
                {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(',')
                })

                if(res.meta.status !== 200){
                return this.$message.error('修改参数项失败')
                }else{
                this.$message.success('修改参数项成功')
                }
            },

            // 点击按钮展示文本输入框
            showInput(row){
                  row.inputVisible = true;
                  this.inputVisible = true;
                  // 让文本框自动获得焦点
                  // $nextTick 方法的作用，就是当页面上的元素被重新渲染后，才会指定回调函数中的代码
                  this.$nextTick(_ => {
                  this.$refs.saveTagInput.$refs.input.focus();
                  });
            },
            
            // 删除对应的参数可选项
            closeHand(i,row){
              row.attr_vals.splice(i, 1)
              this.saveAttrVals(row)
            }          
            },

            // 计算属性来禁止按钮是否dis
            computed: {
                btnsDisabled(){
                if(this.catelistmodel.length !==3){
                return true
                }else {
                return false
                }
                },

             // 获取参数列表数据的id
             btnsParameter(){
             if(this.catelistmodel.length === 3){ 
               return this.catelistmodel[2]
             }
              return rull
             },

             //动态获取动态参数和属性的名字         method方法里面装的是什么，为什么把这个函数放在方面，写在method方法里面就报错
             addParams(){
             if(this.activeName === 'many'){
             return '动态参数'
             }
             return '静态参数'
             },
            }

        }
</script>


<style lang="less" scoped>
   .el-form-item {
       margin-top: 15px;
   }

   .el-tag {
     margin-right: 10px;
   }

   .input-new-tag{
     width: 100px;
   }
</style>